<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<script>
// import { stream } from 'xlsx'
export default {
  name: 'Uploadimg',
  props: {
    staffPhoto: {
      type: String,
      default: () => {}
    }
  },
  data() {
    return {
      imageUrl: ''
    }
  },
  watch: {
    staffPhoto: {
      handler(newVal) {
        this.imageUrl = newVal
      },
      immediate: true
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    upload(res) {
      var COS = require('cos-js-sdk-v5')

      // SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
      var cos = new COS({
        SecretId: 'AKIDJSLxINCk11lEQKzNVM1PZS4PTGl0xd2A',
        SecretKey: 'sjJcfQu73i5B0XnmTu3wYuylGUS8XfW6'
      })
      cos.putObject({
        Bucket: 'web69-1309207043', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: res.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: res.file, // 上传文件对象
        onProgress: function(progressData) {
          console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        console.log(err || data)
        console.log(data, 255555)
        this.imageUrl = 'https://' + data.Location
        this.$emit('uploadSuccess', this.imageUrl)
      })
    }
  }
}
</script>
